import React, { Component } from 'react';
import NarBar from './navbar';
import Boxes from './boxes';

class App extends Component {
    state = {
        boxes: [
            { id: 1, x: 1 },
            { id: 2, x: 2 },
            { id: 3, x: 3 },
            { id: 4, x: 4 },
        ],
        BoxCount: 4
    }

    constructor() {
        super();
        // console.log("App Constructor");
    }

    componentDidMount() {
        // console.log("App Mount");
    }

    componentDidUpdate() {
        // console.log("App Update");
    }

    componentWillUnmount() {
        console.log("App Unmount");
    }

    ClickLeft = (box, step = 1) => {
        let boxes = [...this.state.boxes];
        const k = boxes.indexOf(box);
        boxes[k] = { ...boxes[k] }
        boxes[k].x -= step;
        this.setState({
            boxes
        })
    };

    ClickRight = (box, step = 1) => {
        let boxes = [...this.state.boxes];
        const k = boxes.indexOf(box);
        boxes[k] = { ...boxes[k] }
        boxes[k].x += step;
        this.setState({
            boxes
        })
    };

    ClickDelete = (box) => {
        const boxes = this.state.boxes.filter(b => (b.id !== box.id));
        this.setState({ 
            boxes, 
            BoxCount: this.state.BoxCount - 1,
        });
        
    }

    ClickReset = () => {
        // let boxes = [...this.state.boxes];
        // for (let i in boxes) {
        //     boxes[i] = { ...boxes[i] };
        //     boxes[i].x = 0;
        // }
        const boxes = this.state.boxes.map(box => ({
            id: box.id,
            x: 0,
        }))
        this.setState({ boxes });
    }

    render() {
        console.log("App Render");
        return (<React.Fragment>
            <NarBar BoxCount={this.state.BoxCount}/>
            <div className='container'>
                <Boxes 
                    boxes={this.state.boxes} 
                    ClickLeft={this.ClickLeft} 
                    ClickRight={this.ClickRight}
                    ClickReset={this.ClickReset}
                    ClickDelete={this.ClickDelete} 
                />
            </div>
        </React.Fragment>);
    }
}

export default App;